package com.ruoyi.web.websocket;

import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint("/ws/online")
public class WebSocketServer {
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    public static void sendMessageToUser(String message) throws IOException {
        for (Session session : WebSocketUsers.getUsers().values()) {
            if (session.isOpen()) {
                session.getAsyncRemote().sendText(message);
            }
        }
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws Exception {
        String queryString = session.getQueryString();
        WebSocketUsers.put(session.getId(), session);
        if (queryString == null || queryString.isEmpty()) {
            return;
        }

        String token = extractTokenFromQueryString(queryString);
        if (token != null && SecurityUtils.isTokenValid(token)) {
            WebSocketUsers.put(session.getId(), session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
            WebSocketUsers.sendMessageToUserByText(session, "连接成功");
        }
    }

    private String extractTokenFromQueryString(String queryString) {
        String[] params = queryString.split("=");
        if (params.length == 2 && "authorization".equals(params[0])) {
            return params[1];
        }
        return null;
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session) {
//        LOGGER.info("\n 关闭连接 - {}", session);
//        // 移除用户
//        WebSocketUsers.remove(session.getId());
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info("\n 连接异常 - {}", sessionId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(sessionId);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        sendMessageToUser( message);
    }
}